<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>一起听歌</title>
    <link href="/css/xtiper_css/xtiper.css" rel="stylesheet">
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <style>
        #footer {
            height: 40px;
            line-height: 40px;
            position: fixed;
            bottom: 0;
            width: 100%;
            text-align: center;
            background: floralwhite;
            color:black;
            font-family: Arial;
            font-size: 12px;
            letter-spacing: 1px;
        }
        *{
            margin: 0;
            padding: 0;
        }
        #queue table td{
            align:center
        }
    </style>
</head>
<body style="background-image: url('/music/1623926830(1).jpg');background-size: 100%">

<div class="container panel-body">
    <div class="container" style="text-align: center">
        <span id="userFlag"><span style="color: yellow">大厅游客</span>🅱🟡</span>
        <h1 style="color:ghostwhite">ZIYOU Music</h1>
        <audio src="/music/yrzrz.mp3" id="player" controls="controls" autoplay="autoplay" controlsList="nodownload" οncοntextmenu="return false" style="background-color: antiquewhite"></audio><br>
        <div class="row">
            <span id="musicName" style="font-size: 18px;font-weight: bolder;vertical-align: middle">当前播放:庸人自扰之-花粥</span>
            <br><br><button onclick="changeMusic()" class="btn btn-info" style="vertical-align: middle;margin-left: 20px">切换音乐</button>
            &nbsp;<button onclick="hidQueue()" class="btn btn-info" style="vertical-align: middle;margin-left: 20px">播放队列</button>
            &nbsp;<button onclick="hidChat()" class="btn btn-info" style="vertical-align: middle;margin-left: 20px">边听边聊</button>
            &nbsp;<button onclick="hidSearch()" class="btn btn-info" style="vertical-align: middle;margin-left: 20px">音乐搜索</button>
            <br><br>
        </div>


        <span id="lyric" style="font-size: 18px;height: 30px;width: 400px;color: whitesmoke;font-weight: bolder"></span><br>
            <div id="searchDiv" style="display:none">
                <div class="" style="margin-bottom: 10px;margin-top: 20px">
                    <input type="text" placeholder="请输入关键字" class="" style="color:orangered;border-radius: 5px" id="keyword"/>&nbsp;
                    <button type="button" class="btn btn-sm btn-danger" onclick="searchSong('wy')">搜索音乐</button>
                    <button type="button" onclick="searchSong('qq')" style="display: none">搜索QQ音乐</button>
                </div>
                <div id="searchResult" style="overflow: auto;height: 250px;color: white;">

                </div>
            </div>

        <div id="queueDiv" style="display:none">
            <div style="overflow: auto;height: 250px;text-align: center;margin-top: 20px">
                <table id="queue"  class="table-responsive" style="color: whitesmoke;font-size: 15px;font-weight: bolder;overflow: auto;margin: 0 auto">
                    <tr>
                        <td>歌曲名称</td>
                        <td>操作</td>
                    </tr>
                </table>
            </div>
        </div>
        <div id="chatDiv" style="display:none">
            <iframe src="chat.html" style="height: 600px;margin-top:20px;width: 75%;display: inline;opacity: 0.8"></iframe>
        </div>
    </div>
</div>
<div style="height: 20px"></div>
<div class="container"  style="color: whitesmoke;display: flex;width: 75%">


</div>

</div>
<div id="footer">自由|ZIYOU 一起听歌开源平台
    <a type="button" class="btn btn-success" target="_blank"  href="https://gitee.com/lgp521/ziyou">源码仓库</a>
    <a type="button" class="btn btn-error" target="_blank"  href="https://lgp6.cn/board.html">问题反馈</a>
    <button type="button" class="btn btn-success" title="ZIYOU Music规则说明"
            data-container="body" data-toggle="popover" data-placement="top" data-html="true" data-trigger="hover"
            data-content="
        <p>权限说明：只有大厅主人可以切换歌曲、移除队列歌曲；任何人可以点歌、聊天、搜索音乐；</p>
        <p>只有大厅主人暂停、播放时，会影响全厅用户。 大厅主人暂停后重新播放时，所有用户的播放进度将同步至大厅主人的进度，进度偏差一般不超过2秒。</p>
        <p>大厅主人的选举：在大厅没有人时，第一个进入大厅的为大厅主人；在大厅有人时，一定有大厅主人；当大厅主人离开页面、刷新页面时，重新选举大厅主人；选举大厅主人时，按照进入大厅的顺序，最早进入大厅的为新的大厅主人；刷新页面时视为新进入大厅的用户，顺序排在最后一位；</p>">
        ZIYOU Music规则说明
    </button>

    <button type="button" class="btn btn-warning" title="ZIYOU Music免责声明"
            data-container="body" data-toggle="popover" data-placement="top" data-html="true" data-trigger="hover"
            data-content="
        <p>资源；本站点内的资源均采自互联网免费开放资源。 如涉及您的版权问题，您可联系站长下架或要求标明出处等。邮箱地址：lgp1022@foxmail.com</p>
        <p>观点：本站点内发布的所有信息均为用户主观发布，与本站立场无关。</p>
        <p></p>">
        ZIYOU Music免责说明
    </button>
</div>
</body>
</html>
<script src="/js/jquery-3.4.1.min.js"></script>
<script src="/js/xtiper_js/xtiper.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script>
    var websocket=null;
    var type="normal";
    var isPlay=true;
    var isTb=0;
    var lyricList=null;
    var count=0;
    var searchChannel="wy";
    //判断当前浏览器是否支持WebSocket, 主要此处要更换为自己的地址
    if ('WebSocket' in window) {
        // websocket = new WebSocket("ws://localhost:9411/music/data");
        websocket = new WebSocket("ws://47.103.202.101:9411/music/data");
    } else {
        $('#logArea').append("<br><span style='color: red'>"+new Date()+":当前浏览器不支持一起听歌"+"</span>")
    }
    // $('#logArea').append("<br><span style='color: green'>"+new Date()+":环境:"+"</span>")
    //连接发生错误的回调方法
    websocket.onerror = function () {
        $('#logArea').append("<br><span style='color: red'>"+new Date()+":连接服务器错误"+"</span>")
    };
    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        $('#logArea').append("<br><span style='color: green'>"+new Date()+":初始化环境成功"+"</span>")
    }
    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        var obj=JSON.parse(event.data);
        if (obj.type=="owner"||obj.type=="normal"){
            type=obj.type;
            $.getJSON("https://autumnfish.cn/song/url?id="+obj.current,function (result) {
                $('#player').attr("src",result.data[0].url);
                $('#musicName').html("当前播放:"+obj.musicName);
                setTimeout(function () {
                    isTb=0;
                },1000);
                xtip.msg(obj.msg)
            })
            $.getJSON("/music/lyric/"+obj.current,function (result) {
                count=0;
                lyricList=result;
                $('#lyric').html(obj.musicName);
                clearInterval(lyricInterval);
                lyricProcessStart();
            })
            $('#queue').empty();
            $('#queue').append("<tr><td>歌曲名称</td><td>操作</td></tr>")
            for (let i=0;i<obj.queue.length;i++){
                $('#queue').append("<tr><td>"+obj.queue[i].name+"</td><td><a href='#' class='btn btn-sm btn-warning' onclick='removeQueue(this,"+obj.queue[i].id+")'>移出队列</a></td></tr><tr><td colspan='2'>  -------------------------  &nbsp;</td></tr>")
            }
            if (type=='owner'){
                $('#userFlag').html('<span style="color:red">大厅主人<span>🅰🔴，您拥有本大厅用户的最高权力，同时负有维护大厅秩序的最高义务。')
            }
            }

        if (obj.type=="time"){
           if (type!="owner"){
               currentTime=obj.current;
               isPlay=obj.isPlay;
           }
        }

        if (obj.type=="newOwner"){
            $('#userFlag').html('<span style="color:red">大厅主人<span>🅰🔴，您拥有本大厅用户的最高权力，同时负有维护大厅秩序的最高义务。')
            type="owner";
            xtip.msg(obj.msg)
        }
        if (obj.type=="changeOwner"){
            isTb=0;
            xtip.msg(obj.msg)
        }
        if (obj.type=="pause"){
            $('#player')[0].pause();
            xtip.msg(obj.msg)
        }
        if (obj.type=="play"){
            $('#player')[0].play();
            xtip.msg(obj.msg)
        }
        if (obj.type=="changeOwner"){
            isTb=0;
            xtip.msg(obj.msg)
        }
        if (obj.type=="switch"){
            $.getJSON("https://autumnfish.cn/song/url?id="+obj.current,function (result) {
                $('#player').attr("src", result.data[0].url);
                $('#musicName').html("当前播放:" + obj.musicName);
                setTimeout(function () {
                    isTb = 0;
                }, 1000);
                xtip.msg("切换音乐:" + obj.musicName)
                $('#queue').empty();
                $('#queue').append("<tr><td>歌曲名称</td><td>操作</td></tr>")
                for (let i=0;i<obj.queue.length;i++){
                    $('#queue').append("<tr><td>"+obj.queue[i].name+"</td><td><a href='#' class='btn btn-sm btn-warning' onclick='removeQueue(this,"+obj.queue[i].id+")'>移出队列</a></td></tr><tr><td colspan='2'>  -------------------------  &nbsp;</td></tr>")
                }
            })
            $.getJSON("/music/lyric/"+obj.current,function (result) {
                count=0;
                lyricList=result;
                $('#lyric').html(obj.musicName);
                clearInterval(lyricInterval);
                lyricProcessStart();
            })
        }
        if (obj.type==="changeQueue"){
            $('#queue').empty();
            $('#queue').append("<tr><td>歌曲名称</td><td>操作</td></tr>")
            for (let i=0;i<obj.queue.length;i++){
                $('#queue').append("<tr><td>"+obj.queue[i].name+"</td><td><a href='#' class='btn btn-sm btn-warning' onclick='removeQueue(this,"+obj.queue[i].id+")'>移出队列</a></td></tr><tr><td colspan='2'>  -------------------------  &nbsp;</td></tr>")
            }
            xtip.msg(obj.msg);
        }

    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        xtip.alert("与服务器的连接已关闭,请在约1分钟后重试")
    };
    window.onbeforeunload = function () {
        console.log("1");
        websocket.close();
    }


    var currentTime=0;
    $('#player').on('timeupdate',function () {
      if (type==="owner"){
          websocket.send("current,owner,"+currentTime+","+$('#play'));
          currentTime=this.currentTime;
          // console.log(currentTime);
      }else{
          // console.log("customer");
          if (isTb<=2){
              this.currentTime=currentTime;
              // console.log(isPlay);
              isTb++;
          }
      }
    });
    $('#player').on("pause",function () {
        isPlay=false;
        isTb=0;
        if (type==="owner") {
            websocket.send("pause,owner,0")
        }
    });
    $('#player').on("play",function () {
        isPlay=true;
        count=0;
        if (type==="owner"){
            websocket.send("play,owner,0")
        }else{
            isTb=0;
        }
    });
    $('#player').on("ended",function () {
        isPlay=true;
        if (type==="owner"){
            websocket.send("switch,owner,0")
        }else{
            isTb=0;
        }
    });
    function switchSong(id,name) {
        if (searchChannel==='wy'){
            $.getJSON("https://autumnfish.cn/song/url?id="+id,function (result) {
                // $('#player').attr("src",result.data[0].url);
                // $('#musicName').html("当前播放:"+name);
                if (type==="owner"){
                    $('#queue').append("<tr><td>"+name+"</td><td><a href='#' class='btn btn-sm btn-warning' onclick='removeQueue(this,"+id+")'>移出队列</a></td></tr><tr><td colspan='2'>  -------------------------  &nbsp;</td></tr>")
                    websocket.send("addQueue,owner,"+id+","+name)
                }else{
                    $('#queue').append("<tr><td>"+name+"</td><td><a href='#' class='btn btn-sm btn-warning' onclick='removeQueue(this,"+id+")'>移出队列</a></td></tr><tr><td colspan='2'>  -------------------------  &nbsp;</td></tr>")
                    websocket.send("addQueue,normal,"+id+","+name)
                }
            })
/*            $.getJSON("/music/lyric/"+id,function (result) {
                count=0;
                lyricList=result;
                $('#lyric').val(name);
            })*/
        }else{

        }
    }

    function searchSong(channel) {
        searchChannel=channel;
        if (channel==='wy'){
            $.getJSON("https://autumnfish.cn/search?keywords="+$('#keyword').val(),function (result) {
                $('#searchResult').empty();
                for (var i=0;i<result.result.songs.length;i++){
                    $('#searchResult').append("<br>"+result.result.songs[i].name+"\t|")
                    for (var j=0;j<result.result.songs[i].artists.length;j++){
                        $('#searchResult').append("\t"+result.result.songs[i].artists[j].name+"\t")
                    }
                    $('#searchResult').append("<a href=\"#\" class='btn-sm btn-success' onclick=\"switchSong("+result.result.songs[i].id+",'"+result.result.songs[i].name+"')\">加入播放队列</a><hr>");
                }
            })
        }else{
            $.getJSON("/music/qq/search/"+$('#keyword').val(),function (result) {
                $('#searchResult').empty();
                for (var i=0;i<result.data.song.list.length;i++){
                    $('#searchResult').append("<br>"+result.data.song.list[i].songname+"\t|")
                    for (var j=0;j<result.data.song.list[i].singer.length;j++){
                        $('#searchResult').append("\t"+result.data.song.list[i].singer[j].name+"\t")
                    }
                    $('#searchResult').append("<a href=\"#\" onclick=\"switchSong("+result.data.song.list[i].songid+",'"+result.data.song.list[i].songname+"')\">切换到该歌曲</a>");
                }
            })
        }

    }
    var lyricInterval=null
    function lyricProcessStart(){
        lyricInterval=setInterval(function () {
            for (let i=count;i<lyricList.length;i++){
                // console.log($('#player')[0].currentTime)
                // console.log(lyricList[i].time)
                if ($('#player')[0].currentTime>=lyricList[i].time){
                    // console.log(lyricList[i].lyric);
                    $('#lyric').html(lyricList[i].lyric);
                    count++;
                    break;
                }

            }
        },100)
    }

    function removeQueue(obj,id) {
        if (type!=="owner"){
            xtip.msg("大厅主人才可以操作");
        }else{
            websocket.send("removeQueue,owner,"+id)
            $(obj).parent().parent().remove();
        }
    }
    function changeMusic() {
        if (type==="owner"){
            websocket.send("switch,owner,0")
        }else{
            xtip.msg("只有大厅主人可以切换音乐");
        }
    }

    function hidQueue() {
        if ($('#queueDiv').attr("style")==="display:none"){
            xtip.msg("展示播放队列")
            $('#queueDiv').attr("style","display:block")
        }else{
            xtip.msg("隐藏播放队列")
            $('#queueDiv').attr("style","display:none")
        }
    }
    function hidChat() {
        if ($('#chatDiv').attr("style")==="display:none"){
            xtip.msg("展示边听边聊")
            $('#chatDiv').attr("style","display:block")
        }else{
            xtip.msg("隐藏边听边聊")
            $('#chatDiv').attr("style","display:none")
        }
    }
    function hidSearch() {
        if ($('#searchDiv').attr("style")==="display:none"){
            xtip.msg("展示歌曲搜索")
            $('#searchDiv').attr("style","display:block")
        }else{
            xtip.msg("隐藏歌曲搜索")
            $('#searchDiv').attr("style","display:none")
        }
    }
    $(function () {
        $("[data-toggle='popover']").popover();
    });

</script>
